package com.ruoyi.config.job;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.config.emqx.EmqxApiClient;
import com.ruoyi.mapper.TaskLogMapper;
import com.ruoyi.domain.DeviceDetails;
import com.ruoyi.domain.DeviceEmqxClient;
import com.ruoyi.domain.TaskLog;
import com.ruoyi.service.DeviceDetailsService;
import com.ruoyi.service.TaskInfoService;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 更新传感器设备是否在线-任务
 */
public class LotSynDeviceIsOnlineJob extends QuartzJobBean {

    private static final Logger logger = LoggerFactory.getLogger(LotSynDeviceIsOnlineJob.class);

    @Resource
    TaskLogMapper taskJobMapper;

    @Resource
    EmqxApiClient emqxApiClient;

    @Resource
    TaskInfoService taskInfoService;

    @Resource
    DeviceDetailsService deviceDetailsService;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        String jobName = context.getJobDetail().getKey().getName();
        //1启用 0停用
        if (taskInfoService.isTaskEnabled(jobName) == 1) {
            TaskLog taskLog = new TaskLog();
            taskLog.setJobName(jobName);
            taskLog.setStartTime(new Date());
            Integer count = 0;
            //通过emqx工具类获取目前的设备的信息
            JSONArray onlinCelients = null;
            try {
                onlinCelients = emqxApiClient.getOnlineClients();
                for (int i = 0; i < onlinCelients.size(); i++) {
                    DeviceEmqxClient javaObject = onlinCelients.getJSONObject(i).toJavaObject(DeviceEmqxClient.class);
                    DeviceDetails deviceDetails = new DeviceDetails();
                    deviceDetails.setSensorId(javaObject.getClientid());
                    deviceDetails.setConnectStatus(javaObject.isConnected());
                    deviceDetails.setUpdateTime(new Date());
                    int j = deviceDetailsService.updataConnectStatus(deviceDetails);
                    count = count + j;
                }
                taskLog.setStatus(1);
            } catch (Exception e) {
                taskLog.setStatus(0);
                taskLog.setErrorMessage(e.getMessage());
            } finally {
                taskLog.setBeAffectedCount(count);
                taskLog.setEndTime(new Date());
                taskLog.setUpdateTime(new Date());
                taskJobMapper.insert(taskLog);
            }
        }
    }
}
